﻿<%@ Page Title="" Language="C#" MasterPageFile="~/AdminCP/Layouts/Admin.Master" AutoEventWireup="true"
    CodeBehind="BonusDetailByMonthRecursive.aspx.cs" Inherits="MLM.AdminCP.Pages.BonusDetailByMonthRecursive"
    meta:resourcekey="PageResource1" %>

<%@ Import Namespace="MLM.AdminCP" %>
<asp:Content ID="Content1" ContentPlaceHolderID="head" runat="server">
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" runat="server">
    <%=Resources.MLM.BonusDetailByMonthRecursive %>
</asp:Content>
<asp:Content ID="Content3" ContentPlaceHolderID="ContentPlaceHolder2" runat="server">
    <script type="text/javascript">
        var MLMR = {};
        MLMR.UserId = '<%=Resources.MLM.UserId %>';
        MLMR.Name = '<%=Resources.MLM.Name %>';
        MLMR.Point = '<%=Resources.MLM.Point %>';
        MLMR.Bonus = '<%=Resources.MLM.Bonus %>';
        MLMR.SellingInEuro = '<%=Resources.MLM.SellingInEuro %>';
        MLMR.DiscountForOwnSelling = '<%=Resources.MLM.DiscountForOwnSelling %>';
        MLMR.DifferenceFrom = '<%=Resources.MLM.DifferenceFrom %>';
        MLMR.CarrierBonus = '<%=Resources.MLM.CarrierBonus %>';
        MLMR.LoadingDataPleaseWait = '<%=Resources.MLM.LoadingDataPleaseWait %>';
        MLMR.CalculatingDataForUser = '<%=Resources.MLM.CalculatingDataForUser %>';
        MLMR.PleaseWait = '<%=Resources.MLM.PleaseWait %>';
        MLMR.Total = '<%=Resources.MLM.Total %>'; 
    </script>
    <h3>
        <asp:Label runat="server" ID="lbFilter" Text="Filter" meta:resourcekey="lbFilterResource1"></asp:Label>
    </h3>
    <div>
        <%--<asp:Label runat="server" Text="Level"></asp:Label>
        <telerik:RadNumericTextBox runat="server" Type="Number" ShowSpinButtons="true" DataType="Int32"
            MinValue="0" Value="1" ID="LevelTxt">
            <NumberFormat GroupSeparator="" DecimalDigits="0" />
        </telerik:RadNumericTextBox>--%>
        <asp:Panel runat="server" ID="UserIDPanel" meta:resourcekey="UserIDPanelResource1">
            <asp:Label runat="server" ID="lbUserID" Text="UserID:" meta:resourcekey="lbUserIDResource1"></asp:Label>
            <telerik:RadTextBox runat="server" ID="UserIDTxt" meta:resourcekey="UserIDTxtResource1"
                Width="125px" LabelCssClass="" />
        </asp:Panel>
        <asp:Label runat="server" ID="lbYear" Text=" Year:" meta:resourcekey="lbYearResource1"></asp:Label>
        <telerik:RadComboBox runat="server" ID="FromYearCbb" meta:resourcekey="FromYearCbbResource1" />
        <asp:Label runat="server" ID="lbMonth" Text="Month" meta:resourcekey="lbMonthResource1"></asp:Label>
        <telerik:RadComboBox runat="server" ID="MonthCbb" meta:resourcekey="MonthCbbResource1" />
        <a href="#" class="button" id="btnView">
            <asp:Label runat="server" ID="lbViewbonusdetail" Text="View bonus" meta:resourcekey="lbViewbonusdetailResource1"></asp:Label></a><br />
        <br />
    </div>
    <div id="DetailInfo">
    </div>
    <telerik:RadCodeBlock ID="RadCodeBlock1" runat="server">
        <script type="text/javascript">
            var rankConfig = '<%=GetRanks() %>';
            String.prototype.format = function () {
                var text = this;
                var tokenCount = arguments.length;
                if (tokenCount < 1) {
                    return text;
                }
                for (var token = 0; token < tokenCount; token++) {
                    text = text.replace(new RegExp("\\{" + token + "\\}", "gi"), arguments[token]);
                }
                return text;
            };
            function GetOnlyDate(strDate) {
                strDate = strDate.replace("/Date(", "").replace(")/", "");
                var dt = new Date(parseInt(strDate));
                var date = dt.getDate();
                var mon = dt.getMonth() + 1;
                if (date < 10) date = '0' + date;
                if (mon < 10) mon = '0' + mon;
                return "{0}/{1}/{2}".format(date, mon, dt.getFullYear());
            }
            $(function () {
                $("#btnView").click(function (e) {
                    var userId = $find('<%=UserIDTxt.ClientID %>').get_value();
                    //                     var level = $find('<=LevelTxt.ClientID %>').get_value();
                    var level = 1000;
                    if (userId == '') {
                        alert("Please input UserID!");
                        return false;
                    }
                    var year = $find("<%=FromYearCbb.ClientID %>").get_selectedItem().get_value();
                    var month = $find("<%= MonthCbb.ClientID %>").get_selectedItem().get_value();
                    $.ajax({
                        type: "POST",
                        url: "/AdminCP/Pages/BonusDetailByMonthRecursive.aspx/GetTree",
                        contentType: "application/json; charset=utf-8",
                        dataType: "json",
                        beforeSend: function () {
                            $('body').append('<div id="loadingDiv" style="position:fixed; top:50%; left:50%; width:200px;text-align:center; padding:3px; border:solid 1px #ccc; background:#f1f1f1;">' + MLMR.LoadingDataPleaseWait + '</div>');
                        },
                        data: "{'_level':'" + level + "','_userId':'" + userId + "'}",
                        //data: "{'_year':'" + year + "','_month':'" + month + "','_userId':'" + userId + "'}",
                        async: true,
                        success: function (msj) {
                            var item = JSON.parse(msj.d);
                            var $elm = $('#DetailInfo');
                            $elm.empty();
                            for (var i = 1; i <= item.MaxLevels; i++) {
                                $.each(item.Data, function (j, jtem) {
                                    if (jtem.Level == i) {
                                        if ($elm.find('.ul_item[userid="' + jtem.SponsorId + '"]').length == 0) {
                                            $elm.append('<ul class="ul_item" sponsorid="' + jtem.SponsorId + '" userid="' + jtem.UserId + '" calculated="0"><li class="li_item"><div class="item_info"><span class="item_level">' + jtem.Level + '</span><div class="item_detail"><label>' + MLMR.UserId + ':</label> ' + jtem.UserId + ' <label>' + MLMR.Name + ':</label> ' + jtem.Name + '</div><div class="calculate_detail"><label>' + MLMR.Point + ':</label><span class="item_point">0</span> PV <label>' + MLMR.Bonus + ':</label><span class="item_bonus">0</span> % <label>' + MLMR.SellingInEuro + ':</label><span class="item_selling">0</span> &euro; <span class="total_show_hide" for="' + jtem.UserId + '">' + MLMR.Total + ' <span>0</span> &euro;</span><div class="calculate_detail_money"></div></div></div></li></ul>');
                                        } else {
                                            $elm.find('.ul_item[userid="' + jtem.SponsorId + '"]').append('<ul class="ul_item" sponsorid="' + jtem.SponsorId + '" userid="' + jtem.UserId + '" calculated="0"><li class="li_item"><div class="item_info"><span class="item_level">' + jtem.Level + '</span><div class="item_detail"><label>' + MLMR.UserId + ':</label> ' + jtem.UserId + ' <label>' + MLMR.Name + ':</label> ' + jtem.Name + '</div><div class="calculate_detail"><label>' + MLMR.Point + ':</label><span class="item_point">0</span> PV <label>' + MLMR.Bonus + ':</label><span class="item_bonus">0</span> % <label>' + MLMR.SellingInEuro + ':</label><span class="item_selling">0</span> &euro; <span class="total_show_hide" for="' + jtem.UserId + '">' + MLMR.Total + ' <span>0</span> &euro;</span><div class="calculate_detail_money"></div></div></div></li></ul>');
                                        }
                                    }
                                });
                            }
                            //BindTree(item.Data, item.MaxLevels);
                            CalculateBonus();
                        }
                    });
                    return false;
                });
                $(document).ajaxStop(function () {
                    $('#loadingDiv').remove();
                });
                function BindTree(item, currentLevel, maxLevels) {
                    for (var i = 0; i < maxLevels; i++) {
                        if (item.Level == currentLevel) {
                            var level = 1000;
                            var $elm = $('#DetailInfo');
                            if ($elm.find('.ul_item[userid="' + item.SponsorId + '"]').length == 0) {
                                $elm.append('<ul class="ul_item" sponsorid="' + item.SponsorId + '" userid="' + item.UserId + '" calculated="0"><li class="li_item"><div class="item_info"><span class="item_level">' + item.Level + '</span><div class="item_detail"><label>UserID:</label> ' + item.UserId + ' <label>Name:</label> ' + item.Name + '</div><div class="calculate_detail"><label>Point:</label><span class="item_point">0</span> PV <label>Bonus:</label><span class="item_bonus">0</span> % <label>Selling in &euro;:</label><span class="item_selling">0</span> &euro; <span class="total_show_hide" for="' + item.UserId + '">Total <span>0</span> &euro;</span><div class="calculate_detail_money"></div></div></div></li></ul>');
                            }
                            if (item.RecommendUsers != null) {
                                $.each(item.RecommendUsers, function (j, jtem) {
                                    if (jtem.Level != 0) {
                                        $('.ul_item[sponsorid="' + item.SponsorId + '"] li:first').append('<ul class="ul_item" userid="' + jtem.UserId + '" sponsorid="' + jtem.SponsorId + '" calculated="0"><li class="li_item"><div class="item_info"><span class="item_level">' + jtem.Level + '</span> <div class="item_detail"><label>UserID:</label> ' + jtem.UserId + ' <label>Name:</label> ' + jtem.Name + '</div><div class="calculate_detail"><label>Point:</label><span class="item_point">0</span> PV <label>Bonus:</label><span class="item_bonus">0</span> % <label>Selling in &euro;:</label><span class="item_selling">0</span> &euro; <span class="total_show_hide" for="' + jtem.UserId + '">Total <span>0</span> &euro;</span><div class="calculate_detail_money"></div></div></div></li></ul>');
                                        BindTree(jtem, currentLevel);
                                    }
                                });
                            }
                        }
                    }
                }
                function CalculateBonus() {
                    var userId = $('.ul_item[calculated=0]:first').attr('userid');
                    if (userId != undefined) {
                        $('.ul_item[userid="' + userId + '"] .item_info:first').append('<div class="calculate_loading"></div>');
                        var year = $find("<%=FromYearCbb.ClientID %>").get_selectedItem().get_value();
                        var month = $find("<%= MonthCbb.ClientID %>").get_selectedItem().get_value();
                        $.ajax({
                            type: "POST",
                            url: "/AdminCP/Pages/BonusDetailByMonth.aspx/GetOwnPv",
                            contentType: "application/json; charset=utf-8",
                            dataType: "json",
                            beforeSend: function () {
                                $('body').append('<div id="loadingDiv" style="position:fixed; top:50%; left:50%; width:200px;text-align:center; padding:3px; border:solid 1px #ccc; background:#f1f1f1;">' + MLMR.CalculatingDataForUser + ': ' + userId + '. ' + MLMR.PleaseWait + '</div>');
                            },
                            data: "{'_year':'" + year + "','_month':'" + month + "','_userId':'" + userId + "'}",
                            async: true,
                            success: function (msj) {
                                $('.calculate_loading').remove();
                                $('#loadingDiv').remove();
                                var item = JSON.parse(msj.d);
                                var $elm = $('.ul_item[userid="' + userId + '"]');
                                $elm.attr('calculated', "1");
                                $elm.find('.item_point:first').text(item.Point).attr('myownselling', item.Point);
                                $elm.find('.item_selling:first').text(item.Selling);
                                $elm.find('.item_bonus:first').text(item.Bonus);
                                var total = 0;
                                var myMoney = Number((item.Bonus * item.Point / 100).toFixed(2));
                                total += myMoney;
                                $elm.find('.calculate_detail:first').append('<div class="show_hide_detail"></div>');
                                $elm.find('.calculate_detail_money:first').append('<br /><span class="sub_total_price_label">' + MLMR.DiscountForOwnSelling + ': ' + item.Bonus + '% * ' + item.Point + ' =</span><span class="sub_total_money_get" for="' + item.UserId + '">' + myMoney + '</span> &euro;<br />');
                                var recommendSaleHeadMoney = 0;
                                $.each(item.RecommendUser, function (i, user) {
                                    var userMoney = Number((((item.Bonus - user.Bonus) * user.Point) / 100).toFixed(2));
                                    total += userMoney;
                                    if (user.Bonus === 20) {//20% is sale head                                    
                                        recommendSaleHeadMoney += user.Point;
                                    }
                                    $elm.find('.calculate_detail_money:first').append('<span class="sub_total_price_label" userid="' + userId + '" for="' + item.UserId + '">' + MLMR.DifferenceFrom + ' ' + user.UserId + '(' + user.Name + '): <span class="difference_bonus" userid="' + user.UserId + '" mybonus="' + item.Bonus + '" for="' + item.UserId + '">' + (item.Bonus - user.Bonus) + '</span> % =</span><span class="sub_total_money_get" userid="' + user.UserId + '" for="' + item.UserId + '">' + userMoney + '</span> &euro;<br />');
                                });
                                var carierBonusMoney = 0;
                                var differencePointFromRequired = parseFloat(item.CarrierBonus.MinPVRequire) - parseFloat(item.Point);
                                if (differencePointFromRequired < 0 || isNaN(differencePointFromRequired)) {
                                    differencePointFromRequired = 0;
                                }
                                var subBonus = '';
                                if (item.CarrierBonus.NumberOfSalesHead == 1 && parseFloat(item.Point) > parseFloat(item.CarrierBonus.MinPVRequire)) {
                                    carierBonusMoney = parseFloat(item.CarrierBonus.Bonus) * parseFloat(item.Point) / 100;
                                } else if (item.CarrierBonus.NumberOfSalesHead == 2) {
                                    carierBonusMoney = (recommendSaleHeadMoney - differencePointFromRequired) * (item.CarrierBonus.Bonus / 100) * 50 / 100;
                                    subBonus = ' = 50%';
                                } else if (item.CarrierBonus.NumberOfSalesHead == 3) {
                                    carierBonusMoney = (recommendSaleHeadMoney - differencePointFromRequired) * (item.CarrierBonus.Bonus / 100) * 70 / 100;
                                    subBonus = ' = 70%';
                                }
                                else if (item.CarrierBonus.NumberOfSalesHead >= 4) {
                                    carierBonusMoney = (recommendSaleHeadMoney - differencePointFromRequired) * (item.CarrierBonus.Bonus / 100);
                                }
                                carierBonusMoney = Number((carierBonusMoney).toFixed(2));
                                if (isNaN(carierBonusMoney)) {
                                    carierBonusMoney = 0;
                                }
                                total += carierBonusMoney;
                                if (isNaN(total)) {
                                    total = 0;
                                }
                                $elm.find('.calculate_detail_money:first').append('<span class="sub_total_price_label">' + MLMR.CarrierBonus + ' ' + item.CarrierBonus.Bonus + '% (' + item.CarrierBonus.NumberOfSalesHead + ' sales head ' + subBonus + ') = </span><span class="sub_total_money_get" for="' + item.UserId + '">' + carierBonusMoney + '</span> &euro;<br />');
                                $elm.find('.calculate_detail_money:first').append('<br /><b>Total: </b><span class="total_marketing_get_on_euro" for="' + item.UserId + '">' + Number((total).toFixed(2)) + '</span> &euro;');

                                CalculateBonus();
                                ReCalculateDifferenceBonus();
                                $('.show_hide_detail').off('click').on('click', function () {
                                    if ($(this).hasClass('show_hide_show')) {
                                        $(this).removeClass('show_hide_show');
                                        $(this).parent().find('.total_show_hide').show();
                                        $(this).parent().find('.calculate_detail_money').hide();
                                    } else {
                                        $(this).addClass('show_hide_show');
                                        $(this).parent().find('.total_show_hide').hide();
                                        $(this).parent().find('.calculate_detail_money').show();
                                    }
                                });

                            }
                        });
                    }
                }
                function ReCalculateDifferenceBonus() {
                    if ($('.ul_item[calculated=0]').length == 0) {
                        try {
                            ReCalculatePoint();
                        } catch (e) {
                            console.log(e);
                        }
                        $('.show_hide_detail').show();
                        $('.difference_bonus').each(function () {
                            var userId = $(this).attr('userid');
                            var forUser = $(this).attr('for');
                            var $this = $(this);
                            var point = 0;
                            var grouppoint = parseFloat($('.ul_item[userid="' + userId + '"] .item_point:first').text());
                            $('.ul_item[userid="' + userId + '"] .item_point').each(function () {
                                //  point += parseFloat($(this).text());
                                point += parseFloat($(this).attr('myownselling'));
                            });
                            if (point >= 0) {
                                var bonus = GetBonusFromPoint(point);
                                var difference = parseFloat($this.attr('mybonus')) - parseFloat(bonus);
                                $this.attr('childbonus', bonus);
                                if (difference < 0) {
                                    difference = 0;
                                }
                                var money = parseFloat($('.ul_item[userid="' + userId + '"] .item_selling:first').text());
                                $('.difference_bonus[userid="' + userId + '"]:first').text(difference);
                                $('.sub_total_money_get[userid="' + userId + '"]:first').text(Number((difference * grouppoint / 100).toFixed(2)));
                                var total = 0;
                                $('.sub_total_money_get[for="' + forUser + '"]').each(function () {
                                    total += parseFloat($(this).text());
                                });
                                $('.total_marketing_get_on_euro[for="' + forUser + '"]').text(Number((total).toFixed(2)));
                            }
                        });
                        $('.total_marketing_get_on_euro').each(function () {
                            var forUser = $(this).attr('for');
                            var total = parseFloat($(this).text());
                            if (isNaN(total)) {
                                total = 0;
                            }
                            $('.total_show_hide[for="' + forUser + '"] span').text(Number((total).toFixed(2)));
                            $('.total_show_hide[for="' + forUser + '"]').show();
                        });
                    }
                }
                function ReCalculatePoint() {
                    $('.ul_item .li_item .item_point').each(function () {
                        var $item = $(this);
                        var point = parseInt($item.text());
                        var ownpoint = parseFloat($item.text());
                        var myId = $item.parents('.ul_item:first').attr('userid');
                        //console.log(myId);
                        $('.ul_item[sponsorid="' + myId + '"] .item_point').each(function () {
                            $subItem = $(this);
                            //console.log($subItem.text());
                            point = parseInt(point) + parseInt($subItem.text());
                        });
                        var bonus = GetBonusFromPoint(point);
                        //console.log(bonus);
                        console.log('id:' + myId + ' - ownpoint:' + ownpoint + ' - bonus:' + bonus);
                        $item.parent().find('.item_bonus').text(bonus);
                        $item.text(point);
                        $('.difference_bonus[for="' + myId + '"]').attr('mybonus', bonus);
                        $item.parent().find('.calculate_detail_money .sub_total_price_label:first').text(MLMR.DiscountForOwnSelling + ': ' + bonus + '% *' + ownpoint);
                        $item.parent().find('.calculate_detail_money .sub_total_money_get:first').text(bonus * ownpoint / 100);
                    });
                }
                function GetBonusFromPoint(point) {
                    if (point == 0) { return 0; }
                    var obj = JSON.parse(rankConfig);
                    var returnBonus = 0;
                    $.each(obj, function (i, item) {
                        if (parseFloat(point) >= parseFloat(item.MinPV) && parseFloat(item.Bonus) > returnBonus) {
                            returnBonus = parseFloat(item.Bonus);
                        }
                    });
                    return returnBonus;
                }
            });            
        </script>
    </telerik:RadCodeBlock>
    <style type="text/css">
        #MyInfoDiv { width: 200px; border: solid 1px #ccc; background: #f1f1f1; padding: 5px 10px; float: left; margin: 5px; }
        #MyInfoDiv span { width: 100px; display: inline-block; }
        #MySponsorDiv { display: inline-block; width: 100%; }
        .total_marketing_get_on_euro { font-size: 20px; color: orangered; }
        .sub_total_money_get { display: inline-block; font-weight: bold; text-align: right; width: 140px; }
        .sub_total_price_label { display: inline-block; margin-bottom: 10px; width: 400px; font-weight: normal; }
        .ul_item { border-left: 1px dotted #CCCCCC; padding-left: 20px; }
        .item_info { background: none repeat scroll 0 0 #F1F1F1; color: #222222; font-weight: bold; margin: 2px; padding: 5px; position: relative; }
        .li_item { list-style-type: none; }
        .item_level { background: none repeat scroll 0 0 #FFFFFF; color: #999999; margin-right: 10px; padding: 3px; }
        .item_detail { display: inline-block; }
        .item_detail label { color: #666; }
        .calculate_loading { background: url("/images/ajax-loader.gif") no-repeat scroll 0 0 transparent; display: inline-block; float: right; height: 11px; left: -20px; position: absolute; top: 10px; width: 16px; }
        .calculate_detail { margin-top: 2px; color: #666; background: #fff; padding: 5px; margin-top: 5px; }
        .calculate_detail label { display: inline-block; margin-left: 25px; margin-right: 5px; }
        .item_point { color: green; }
        .item_bonus { color: orange; }
        .item_selling { color: peru; }
        .calculate_detail_money { display: none; text-align: right; border-top: solid 1px #ddd; font-weight: normal; }
        .show_hide_detail { background: url(/images/sprite-expand-collapse.png) no-repeat; cursor: pointer; display: inline-block; float: right; height: 15px; opacity: 0.7; position: absolute; right: 8px; top: 6px; width: 14px; display: none; }
        .show_hide_detail:hover { opacity: 1; }
        .show_hide_show { background-position: 0 -15px; }
        .total_show_hide { display: none; float: right; }
        .total_show_hide span { font-size: 15px; color: orangered; }
    </style>
</asp:Content>
